//
//  SISSHouseEnrollSecondViewController.m
//  SISSAPP
//
//  Created by 袁应荣 on 2018/8/6.
//  Copyright © 2018年 优房网. All rights reserved.
//

#import "SISSHouseEnrollSecondViewController.h"
#import "SWForm.h"
#import "SISSJsonRequestNetworkingManager+Registration.h"
#import "SISSHouseEnrollSecondViewModel.h"

#import "SISSEnrollHouseDetailViewController.h"
#import "SISSCooperationDetailViewController.h"
#import "SISSMyEnrollHouseViewController.h"

@interface SISSHouseEnrollSecondViewController ()

/// viewModel
@property (weak, nonatomic) SISSHouseEnrollSecondViewModel *viewModel;

/** 记录是否点击了确定 */
@property (assign, nonatomic) BOOL isConfirm;

@end

@implementation SISSHouseEnrollSecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.title = @"房源登记";
    // 添加左侧的关闭按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"关闭"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    
    [self initUI];
}

/**
 返回关闭按钮的点击事件
 */
- (void)back {
    
    [self.view endEditing:YES];
    
//    if (self.isConfirm) { // 判断是否点击了确定
//        [self dismissViewControllerAnimated:YES completion:nil];
//        [self.navigationController popViewControllerAnimated:YES];
//    } else {
        NSString *title = @"放弃";
        NSString *message = self.houseModel ? @"修改还未完成，您确定放弃吗？" : @"登记还未完成，您确定放弃吗？";
    
    [self alertConfirmCacellActionAlertWithTitle:title message:message];
//    }
    
}

- (BOOL)contentShouldChangeTextWithCell:(SWFormBaseCell *)cell text:(NSString *)text {
    
    NSIndexPath *indexPath = [self.formTableView indexPathForCell:cell];
    
    // 售价
    if (indexPath.section == 1 && indexPath.row == 0 && text.length > 9) {
        [self alertActionAlertWithTitle:@"提示" message:@"售价不能超过9位数字"];
//        [SISSTools showSVTitle:@"售价不能超过9位数字" andTime:1 andColor:YES];
        return NO;
    }
    // 面积
    if (indexPath.section == 1 && indexPath.row == 3 && text.length > 9) {
        [self alertActionAlertWithTitle:@"提示" message:@"建筑面积不能超过9位数字"];
//        [SISSTools showSVTitle:@"建筑面积不能超过9位数字" andTime:1 andColor:YES];
        return NO;
    }
    if (indexPath.section == 1 && indexPath.row == 4 && text.length > 9) {
        [self alertActionAlertWithTitle:@"提示" message:@"套内面积不能超过9位数字"];
//        [SISSTools showSVTitle:@"套内面积不能超过9位数字" andTime:1 andColor:YES];
        return NO;
    }
    
    // 名字
    if (indexPath.section == 4 && indexPath.row == 2 && text.length > 11) {
        [self alertActionAlertWithTitle:@"提示" message:@"手机号码不能超过11位数"];
        //        [SISSTools showSVTitle:@"姓名不能少于2个字" andTime:1 andColor:YES];
    }
    
    if (indexPath.section == 3 && indexPath.row == 0 && text.length > 500) {
        [self alertActionAlertWithTitle:@"提示" message:@"需求说明不能超过500个字"];
//        [SISSTools showSVTitle:@"需求说明不能超过500个字" andTime:1 andColor:YES];
        return NO;
    }
    
    return YES;
}

- (void)contentDidChangeTextWithCell:(SWFormBaseCell *)cell text:(NSString *)text {
    NSIndexPath *indexPath = [self.formTableView indexPathForCell:cell];
    
    // 套内面积大于建筑面积
    if (self.viewModel.floorAreaItem.info.length > 0 && self.viewModel.teachingAreaItem.info.length > 0 && ((indexPath.section == 1 && indexPath.row == 3) || (indexPath.section == 1 && indexPath.row == 4)) && [self.viewModel.floorAreaItem.info integerValue] < [self.viewModel.teachingAreaItem.info integerValue] ) {
        [self alertActionAlertWithTitle:@"提示" message:@"套内面积不能小于建筑面积"];
//        [SISSTools showSVTitle:@"套内面积不能小于建筑面积" andTime:1 andColor:YES];
    }
    // 名字
    if (indexPath.section == 4 && indexPath.row == 0 && text.length < 2) {
        [self alertActionAlertWithTitle:@"提示" message:@"姓名不能少于2个字"];
        //        [SISSTools showSVTitle:@"姓名不能少于2个字" andTime:1 andColor:YES];
    }
}



/**
 下一步按钮点击事件
 */
- (void)nextStepButtonClickAction {
    // 这里只是简单描述校验逻辑，可根据自身需求封装数据校验逻辑
    [SWFormHandler jyt_checkFormNullDataWithWithDatas:self.mutableItems success:^{
        
         self.houseModel.neighbourhood = self.viewModel.communityItem.info;
         self.houseModel.bnum = self.viewModel.buildingItem.info;
         self.houseModel.dnum = self.viewModel.roomItem.info;
        self.houseModel.price = self.viewModel.priceItem.info;
//        self.houseModel.averagePrice = [self.priceTextField.text floatValue] / [self.areaTextField.text floatValue];
        self.houseModel.propertyState = self.viewModel.propertyItem.info;
        self.houseModel.houseType = self.viewModel.houseTypeItem.info;
//        self.houseModel.area = [self.viewModel.text floatValue]; // 建筑面积
//        self.houseModel.area = [self.viewModel.text floatValue]; // 套内面积

        self.houseModel.year = self.viewModel.buildingYearItem.info.length > 0 ? [self.viewModel.buildingYearItem.info substringToIndex:self.viewModel.buildingYearItem.info.length - 1] : @"";
        self.houseModel.direction = self.viewModel.directionItem.info ? self.viewModel.directionItem.info : @"";
        self.houseModel.decoration = self.viewModel.decorationItem.info ? self.viewModel.decorationItem.info : @"";
        NSString *houseTagStr = self.viewModel.houseTagItem.info ? self.viewModel.houseTagItem.info : @"";
        NSArray *tagArr = [houseTagStr componentsSeparatedByString:@" "];
        NSMutableArray *listTag = [NSMutableArray arrayWithCapacity:tagArr.count];
        NSInteger count = tagArr ? tagArr.count - 1 : 0;
        for (NSInteger i = 0; i < count; i++) {
            SISSHouseResourceTagModel *tagModel = [[SISSHouseResourceTagModel alloc] init];
            tagModel.tag = tagArr[i];
            tagModel.color = [self.viewModel.tagIndexArray[i] integerValue] + 1;
            [listTag addObject:tagModel];
        }
        self.houseModel.listTag = listTag;
        self.houseModel.contractNo = self.viewModel.contractNoItem.info;
        self.houseModel.houseInfoNo = self.viewModel.houseInfoCodeItem.info;
        self.houseModel.otherdesc = self.viewModel.otherdescItem.info;
        self.houseModel.name = self.viewModel.sellerNameItem.info;
        self.houseModel.phoneNumber = self.viewModel.sellerPhoneNumItem.info;
        self.houseModel.insertTime = [NSDate yyr_dateCurrentTimeString]; // 获取系统的当前时间
        
        [SISSPublicSingleton shared].isHud = NO;//
        if (self.isModify) {
            
            self.houseModel.asId = self.houseModel.asId;
            self.houseModel.ID = self.houseModel.ID;
            self.houseModel.asoId = self.houseModel.asoId;
            
            [self updateHouseWithHouseModel:self.houseModel];
        } else {
            [self enrollHouseWithHouseModel:self.houseModel];
        }
        
    } failure:^(NSString *error) {
        NSLog(@"error====%@",error);
    }];
}


/**
 登记房源
 */
- (void)enrollHouseWithHouseModel:(SISSHouseResourceModel *)houseModel {
    
    
    [kJsonRequestNetworkingManager enrollHouseResourceWithHouseModel:houseModel successBlock:^(id responseObject) {
        
        NSLog(@"登记房源===>>>>%@",responseObject);
        
        if ([responseObject[@"code"] integerValue] == 0) {
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                [SISSTools showSVTitle:responseObject[@"message"] andTime:1.0 andColor:YES];
            }];
            return ;
        }
        
        if ([responseObject[@"code"] integerValue] == 200) { // 登记成功
            [SISSTools showSVTitle:@"登记成功！" andTime:1.0 andColor:YES];
            self.isConfirm = YES;
            if (self.isRegistration) {
                
                if (self.isCooperation) {
                    SISSCooperationDetailViewController *vc = [[SISSCooperationDetailViewController alloc] init];
                    vc.houseModel = houseModel;
                    [self.navigationController pushViewController:vc animated:YES];
                } else {
                    SISSEnrollHouseDetailViewController *vc = [[SISSEnrollHouseDetailViewController alloc] init];
                    vc.title = @"房源详情";
                    vc.houseResourceModel = houseModel;
                    vc.isChange = NO;
                    vc.deleteComplete = ^{
                        
                        [self dismissViewControllerAnimated:YES completion:nil];
                    };
                    
                    [self.navigationController pushViewController:vc animated:YES];
                }
                
            } else {
                
                [self.navigationController popViewControllerAnimated:YES];
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        } else { // 登记失败
            
            [SISSTools showSVErrorTitle:@"登记失败" andTime:2 andColor:YES];
        }
        
    } failed:^(NSError *error) {
        
        NSLog(@"客源登记error: %@",error);
    }];
}


/**
 修改房源
 */
- (void)updateHouseWithHouseModel:(SISSHouseResourceModel *)houseModel {
    
    [kJsonRequestNetworkingManager updateHouseResourceWithHouseModel:houseModel successBlock:^(id responseObject) {
        
        if ([responseObject[@"code"] integerValue] == 200) { // 修改成功
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                
                [SISSTools showSVTitle:@"修改成功！" andTime:1.0 andColor:YES];
            }];
            
            for (UIViewController *controller in self.navigationController.viewControllers) {
                if ([controller isKindOfClass:[SISSMyEnrollHouseViewController class]]) {
                    [self.navigationController popToViewController:controller animated:YES];
                }
            }
        }
        
    } failed:^(NSError *error) {
        
        NSLog(@"%@",error);
    }];
}

#pragma mark - 数据请求
- (void)setLandId:(NSString *)landId {
    _landId = landId;
    if (landId.length > 0) {
        [kJsonRequestNetworkingManager requestHouseDetailsInfoWithLandId:landId successBlock:^(SISSHouseDetailsInfoModel *houseDetailsInfo) {
            
            self.viewModel.houseTypeItem.info = houseDetailsInfo.huxing;
            self.viewModel.floorAreaItem.info = houseDetailsInfo.bsqar;
            self.viewModel.teachingAreaItem.info = houseDetailsInfo.inside;
            self.viewModel.directionItem.info = houseDetailsInfo.direct;
            
            [self.formTableView reloadData];
            
        } failed:^(NSError *error) {
            NSLog(@"%@",error);
        }];
    }
}


#pragma mark - UI
- (void)initUI {
    
    self.formTableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    SISSHouseEnrollSecondViewModel *viewModel = [[SISSHouseEnrollSecondViewModel alloc] initWithController:self];
    viewModel.houseModel = self.houseModel;
    self.viewModel = viewModel;
    self.mutableItems = [viewModel dataSource];
    
    self.formTableView.tableHeaderView = [self headerView];
    self.formTableView.tableFooterView = [self footerView];
    [self.formTableView layoutIfNeeded];
    
}


/**
 创建header
 */
- (UIView *)headerView {
    UIView *headView = [[UIView alloc] init];
    UILabel *label = [[UILabel alloc] init];
    label.text = @"温馨提示：请确保您登记的信息真实有效，发现弄虚作假的将记录不良行为。";
    label.textColor = MAIN_TEXT_COLOR;
    label.numberOfLines = 0;
    label.font = [UIFont systemFontOfSize:17];
    label.preferredMaxLayoutWidth = SCREEN_WIDTH - 26;
    [headView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(@16);
        make.bottom.right.equalTo(@(-18));
    }];
    CGFloat height = [headView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    CGRect frame = headView.bounds;
    frame.size.height = height;
    headView.frame = frame;
    return headView;
}

/**
 创建footer
 */
- (UIView *)footerView {
    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 80)];
    
    UIButton *nextStepButton = [UIButton buttonWithType:UIButtonTypeSystem];
    nextStepButton.bounds = CGRectMake(0, 0, SCREEN_WIDTH * 0.8, 40);
    nextStepButton.center = footer.center;
    nextStepButton.backgroundColor = MAIN_COLOR;
    nextStepButton.layer.cornerRadius = 8;
    nextStepButton.layer.masksToBounds = YES;
    [nextStepButton setTitle:@"下一步" forState:UIControlStateNormal];
    [nextStepButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [nextStepButton addTarget:self action:@selector(nextStepButtonClickAction) forControlEvents:UIControlEventTouchUpInside];
    [footer addSubview:nextStepButton];
    
    return footer;
}




@end
